package com.marver.common.result;

import com.fasterxml.jackson.annotation.JsonInclude;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Result {
	private int code=0;
	private Message message;
	@JsonInclude(JsonInclude.Include.NON_EMPTY)
	private Page page;
	@JsonInclude(JsonInclude.Include.NON_EMPTY)
	private List data;

	public Page getPage() {
		return page;
	}
	public void setPage(Page page) {
		this.page = page;
	}
	public Result(){
		
	}
	public Result(int code){
		this.code=code;
		this.message = new Message();
		this.message.setTip(ResultStatus.getMsg(code));
	}
	
	public Result(int code,List data){
		this.code=code;
		this.message = new Message();
		this.message.setTip(ResultStatus.getMsg(code));
		this.data=data;
		this.setPage(new Page((this.data.size()>0?1:0),0,this.data.size()));
	}

	/**
	 * 不需要分页 单条数据
	 * @param code
	 * @param data
	 */
	public Result(int code,Object data){
		//判断是否String
		if (data instanceof String||data.getClass().getName().equals("java.lang.String")) {
			this.code=Integer.valueOf(code);
			this.message = new Message();
			this.message.setTip((String)data);
		}else {
			this.code = code;
			this.message = new Message();
			this.message.setTip(ResultStatus.getMsg(code));
			List list = new ArrayList();
			list.add(data);
			this.data = list;
		}
	}
	
	public Result(int code,List data,Page page){
		this.code=code;
		this.message = new Message();
		this.message.setTip(ResultStatus.getMsg(code));
		this.data=data;
		this.page=page;
	}
	
	public Result(String code,String tip){
		this.code=Integer.valueOf(code);
		this.message = new Message();
		this.message.setTip(tip);
	}

	public Result(int code,Message message){
		this.code=Integer.valueOf(code);
		this.message = message;
	}

	/**
	 * 统一数据验证错误显示
	 * @param result
	 * @return
	 */
	public static Result validation(int code , BindingResult result) {
		List errorList = new ArrayList();
		for (FieldError error : result.getFieldErrors()) {
			Map<String, String> item = new HashMap<>();
			item.put(error.getField(), error.getDefaultMessage());
			errorList.add(item);
		}
		return new Result(code ,errorList);
	}
	
	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public Message getMessage() {
		return message;
	}

	public void setMessage(Message message) {
		this.message = message;
	}
	public List getData() {
		return data;
	}
	public void setData(List data) {
		this.data=data;
	}
}
